#!/usr/bin/env python3
# set coding: utf-8
"""
@Project : ywpt
@File :    init.py
@Time :    2025/5/12 14:11
@Author :  richard zhu
@Email :   gaotao.zhugt@dtzhejiang.com
@purpose : 初始化默认配置
"""

from django.core.management.base import CommandError, BaseCommand
from system.models import SysRole, SysMenu, SysRoleMenu, SysUser, SysUserRole
from django.utils import timezone
from django.db.utils import IntegrityError

class Command(BaseCommand):
    help = "初始化默认配置"

    def handle(self, *args, **kwargs):
        default_admin = {
            "username": "admin",
            "password": "YGreTh59cIPN",
            "email": "admin@123.com",
            "is_staff": True,
            "is_superuser": True
        }
        try:
            # 创建管理员用户
            admin_user = SysUser.objects.create_superuser(
                **default_admin
            )
            self.stdout.write(self.style.SUCCESS(f"创建管理员用户: {default_admin['username']},默认密码: {default_admin['password']}"))
        except IntegrityError as e:
            # 检查是否是用户名重复错误
            if "Duplicate entry" in str(e) and "username" in str(e):
                self.stdout.write(self.style.WARNING(f"管理员用户已存在，跳过创建"))
                admin_user = SysUser.objects.get(username="admin")
            else:
                # 其他完整性错误
                self.stdout.write(self.style.ERROR(f"创建管理员用户失败: {e}"))
        else:
            self.stdout.write(self.style.SUCCESS(f"创建管理员用户成功"))

        try:
            # 创建管理员角色
            admin_role = SysRole.objects.create(
                name="管理员",
                code="admin",
                remark="管理员角色"
            )
            self.stdout.write(self.style.SUCCESS(f"创建管理员角色: {admin_role}"))
        except IntegrityError as e:
            # 检查是否是角色名称重复错误
            if "Duplicate entry" in str(e) and "name" in str(e):
                self.stdout.write(self.style.WARNING(f"管理员角色已存在，跳过创建"))
                admin_role = SysRole.objects.get(name="管理员")
            else:
                # 其他完整性错误
                self.stdout.write(self.style.ERROR(f"创建管理员角色失败: {e}"))
        else:
            self.stdout.write(self.style.SUCCESS(f"创建管理员角色成功"))
            
        try:
            # 创建菜单
            system_menu = SysMenu.objects.create(
                name="系统管理",
                icon="system",
                parent_id=0,
                order_num=20,
                path="/sys",
                menu_type="M",
                api_path="/system",
                create_time=timezone.now(),
                update_time=timezone.now(),
                remark="系统管理"
            )
            self.stdout.write(self.style.SUCCESS(f"创建系统菜单: {system_menu}"))
        except IntegrityError as e:
            # 检查是否是菜单名称重复错误
            if "Duplicate entry" in str(e) and "name" in str(e):
                self.stdout.write(self.style.WARNING(f"系统菜单已存在，跳过创建"))
            else:
                # 其他完整性错误
                self.stdout.write(self.style.ERROR(f"创建系统菜单失败: {e}"))
        else:
            self.stdout.write(self.style.SUCCESS(f"创建系统菜单成功"))

        try:
            # 创建用户菜单
            user_menu = SysMenu.objects.create(
                name="用户管理",
                icon="peoples",
                parent_id=system_menu.id,
                order_num=1,
                path="/system/user",
                menu_type="C",
                api_path="/system/user,/system/user/,/system/user/batch_delete/,/system/user/check/,/system/user/grant_role/,/system/user/modify_password/,/system/user/upload_image/,/system/user/user_role/",
                create_time=timezone.now(),
                update_time=timezone.now(),
                remark="用户管理"
            )
            self.stdout.write(self.style.SUCCESS(f"创建用户菜单: {user_menu}"))
        except IntegrityError as e:
            # 检查是否是菜单名称重复错误
            if "Duplicate entry" in str(e) and "name" in str(e):
                self.stdout.write(self.style.WARNING(f"用户菜单已存在，跳过创建"))
                user_menu = SysMenu.objects.get(name="用户管理")
            else:
                # 其他完整性错误
                self.stdout.write(self.style.ERROR(f"创建用户菜单失败: {e}"))
        else:
            self.stdout.write(self.style.SUCCESS(f"创建用户菜单成功"))

        try:
            # 创建角色菜单
            role_menu = SysMenu.objects.create(
                name="角色管理",
                icon="people",
                parent_id=system_menu.id,
                order_num=2,
                path="/system/role",
                menu_type="C",
                api_path="/system/role,/system/role_menu,/system/role/,/system/role/batch_delete/,/system/role/grant_menu/,/system/role_menu/",
                create_time=timezone.now(),
                update_time=timezone.now(),
                remark="角色管理"
            )
            self.stdout.write(self.style.SUCCESS(f"创建角色菜单: {role_menu}"))
        except IntegrityError as e:
            # 检查是否是菜单名称重复错误
            if "Duplicate entry" in str(e) and "name" in str(e):
                self.stdout.write(self.style.WARNING(f"角色菜单已存在，跳过创建"))
                role_menu = SysMenu.objects.get(name="角色管理")
            else:
                # 其他完整性错误
                self.stdout.write(self.style.ERROR(f"创建角色菜单失败: {e}"))
        else:
            self.stdout.write(self.style.SUCCESS(f"创建角色菜单成功"))

        try:
            # 创建菜单菜单
            menu_menu = SysMenu.objects.create(
                name="菜单管理",
                icon="tree",
                parent_id=system_menu.id,
                order_num=3,
                path="/system/menu",
                menu_type="C",
                api_path="/system/menu,/system/menu_tree,/system/menu/,/system/menu/show_urls/,/system/menu_tree/",
                create_time=timezone.now(),
                update_time=timezone.now(),
                remark="菜单管理"
            )
            self.stdout.write(self.style.SUCCESS(f"创建菜单菜单: {menu_menu}"))
        except IntegrityError as e:
            # 检查是否是菜单名称重复错误
            if "Duplicate entry" in str(e) and "name" in str(e):
                self.stdout.write(self.style.WARNING(f"菜单菜单已存在，跳过创建"))
                menu_menu = SysMenu.objects.get(name="菜单管理")
            else:
                # 其他完整性错误
                self.stdout.write(self.style.ERROR(f"创建菜单菜单失败: {e}"))
        else:
            self.stdout.write(self.style.SUCCESS(f"创建菜单菜单成功"))

        try:
            # 创建系统设置菜单
            config_men = SysMenu.objects.create(
                name="系统设置",
                icon="system",
                parent_id=system_menu.id,
                order_num=4,
                path="/system/config",
                menu_type="C",
                api_path="/system/config",
                create_time=timezone.now(),
                update_time=timezone.now(),
                remark="系统设置"
            )
            self.stdout.write(self.style.SUCCESS(f"创建系统设置菜单: {config_men}"))
        except IntegrityError as e:
            # 检查是否是菜单名称重复错误
            if "Duplicate entry" in str(e) and "name" in str(e):
                self.stdout.write(self.style.WARNING(f"系统设置菜单已存在，跳过创建"))
                config_men = SysMenu.objects.get(name="系统设置")
            else:
                # 其他完整性错误
                self.stdout.write(self.style.ERROR(f"创建系统设置菜单失败: {e}"))
        else:
            self.stdout.write(self.style.SUCCESS(f"创建系统设置菜单成功"))

        self.stdout.write(self.style.SUCCESS(f"创建系统菜单"))
        
        try:
            # 创建日志审计
            log_men = SysMenu.objects.create(
                name="日志审计",
                icon="list",
                parent_id=system_menu.id,
                order_num=6,
                path="/system/logs",
                menu_type="C",
                api_path="/system/oper_log/,/system/oper_log/batch_delete/,/system/oper_log/clean/",
                create_time=timezone.now(),
                update_time=timezone.now(),
                remark="日志审计"
            )
            self.stdout.write(self.style.SUCCESS(f"创建日志管理菜单: {log_men}"))
        except IntegrityError as e:
            # 检查是否是菜单名称重复错误
            if "Duplicate entry" in str(e) and "name" in str(e):
                self.stdout.write(self.style.WARNING(f"日志管理菜单已存在，跳过创建"))
                log_men = SysMenu.objects.get(name="日志管理")
            else:
                # 其他完整性错误
                self.stdout.write(self.style.ERROR(f"创建日志管理菜单失败: {e}"))
        else:
            self.stdout.write(self.style.SUCCESS(f"创建日志管理菜单成功"))

        try:
            # 任务管理
            task_men = SysMenu.objects.create(
                name="任务管理",
                icon="list",
                parent_id=0,
                order_num=13,
                path="/tasks/tasks",
                menu_type="M",
                api_path="/tasks",
                create_time=timezone.now(),
                update_time=timezone.now(),
                remark="任务管理"
            )
            self.stdout.write(self.style.SUCCESS(f"创建任务管理菜单: {task_men}"))
        except IntegrityError as e:
            # 检查是否是菜单名称重复错误
            if "Duplicate entry" in str(e) and "name" in str(e):
                self.stdout.write(self.style.WARNING(f"任务管理菜单已存在，跳过创建"))
                task_men = SysMenu.objects.get(name="任务管理")
            else:
                # 其他完整性错误
                self.stdout.write(self.style.ERROR(f"创建任务管理菜单失败: {e}"))
        else:
            self.stdout.write(self.style.SUCCESS(f"创建任务管理菜单成功"))

        try:
            # 创建任务定义菜单
            task_def_men = SysMenu.objects.create(
                name="任务定义",
                icon="logininfor",
                parent_id=task_men.id,
                order_num=14,
                path="/tasks/task_definition",
                menu_type="C",
                api_path="/tasks/task_definition",
                create_time=timezone.now(),
                update_time=timezone.now(),
                remark="任务定义"
            )
            self.stdout.write(self.style.SUCCESS(f"创建任务定义菜单: {task_def_men}"))
        except IntegrityError as e:
            # 检查是否是菜单名称重复错误
            if "Duplicate entry" in str(e) and "name" in str(e):
                self.stdout.write(self.style.WARNING(f"任务定义菜单已存在，跳过创建"))
                task_def_men = SysMenu.objects.get(name="任务定义")
            else:
                # 其他完整性错误
                self.stdout.write(self.style.ERROR(f"创建任务定义菜单失败: {e}"))
        else:
            self.stdout.write(self.style.SUCCESS(f"创建任务定义菜单成功"))

        try:
            # 创建任务记录菜单
            task_result_men = SysMenu.objects.create(
                name="任务记录",
                icon="date",
                parent_id=task_men.id,
                order_num=15,
                path="/tasks/task_result",
                menu_type="C",
                api_path="/tasks/task_result/,/tasks/task_result/clear_old_results/,/tasks/task_result/task_stats/",
                create_time=timezone.now(),
                update_time=timezone.now(),
                remark="任务记录"
            )
        except IntegrityError as e:
            # 检查是否是菜单名称重复错误
            if "Duplicate entry" in str(e) and "name" in str(e):
                self.stdout.write(self.style.WARNING(f"任务记录菜单已存在，跳过创建"))
                task_result_men = SysMenu.objects.get(name="任务记录")
            else:
                # 其他完整性错误
                self.stdout.write(self.style.ERROR(f"创建任务记录菜单失败: {e}"))
        else:
            self.stdout.write(self.style.SUCCESS(f"创建任务记录菜单成功"))
        

        try:
            # 创建任务列表菜单
            tasks_tasks_men = SysMenu.objects.create(
                name="任务执行",
                icon="list",
                parent_id=task_men.id,
                order_num=14,
                path="/tasks/tasks",
                menu_type="C",
                api_path="/tasks",
                create_time=timezone.now(),
                update_time=timezone.now(),
                remark="任务执行"
            )
        except IntegrityError as e:
            # 检查是否是菜单名称重复错误
            if "Duplicate entry" in str(e) and "name" in str(e):
                self.stdout.write(self.style.WARNING(f"任务列表菜单已存在，跳过创建"))
                tasks_tasks_men = SysMenu.objects.get(name="任务列表")
            else:
                # 其他完整性错误
                self.stdout.write(self.style.ERROR(f"创建任务列表菜单失败: {e}"))
        else:
            self.stdout.write(self.style.SUCCESS(f"创建任务列表菜单成功"))

        try:
            # 创建任务统计菜单
            tasks_bashboard_men = SysMenu.objects.create(
                name="任务统计",
                icon="dashboard",
                parent_id=task_men.id,
                order_num=10,
                path="/tasks/dashboard",
                menu_type="C",
                api_path="/tasks/dashboard",
                create_time=timezone.now(),
                update_time=timezone.now(),
                remark="任务统计"
            )
        except IntegrityError as e:
            # 检查是否是菜单名称重复错误
            if "Duplicate entry" in str(e) and "name" in str(e):
                self.stdout.write(self.style.WARNING(f"任务统计菜单已存在，跳过创建"))
                tasks_bashboard_men = SysMenu.objects.get(name="任务统计")
            else:
                # 其他完整性错误
                self.stdout.write(self.style.ERROR(f"创建任务统计菜单失败: {e}"))
        else:
            self.stdout.write(self.style.SUCCESS(f"创建任务统计菜单成功"))

        # 创建管理员角色菜单
        SysRoleMenu.objects.create(
            role=admin_role,
            menu=system_menu
        )   
        SysRoleMenu.objects.create(
            role=admin_role,
            menu=user_menu
        )
        SysRoleMenu.objects.create(
            role=admin_role,
            menu=role_menu
        )
        SysRoleMenu.objects.create(
            role=admin_role,
            menu=menu_menu
        )
        SysRoleMenu.objects.create(
            role=admin_role,
            menu=config_men
        )
        SysRoleMenu.objects.create(
            role=admin_role,
            menu=task_men
        )
        SysRoleMenu.objects.create(
            role=admin_role,
            menu=task_def_men 
        )
        SysRoleMenu.objects.create(
            role=admin_role,
            menu=task_result_men
        )
        SysRoleMenu.objects.create(
            role=admin_role,
            menu=tasks_tasks_men
        )
        SysRoleMenu.objects.create(
            role=admin_role,
            menu=tasks_bashboard_men
        )

        SysRoleMenu.objects.create(
            role=admin_role,
            menu=log_men
        )
        
        self.stdout.write(self.style.SUCCESS(f"创建管理员角色菜单"))
            
        # 创建管理员绑定角色
        admin_bindrole = SysUserRole.objects.create(
            user=admin_user,
            role=admin_role
        )
        self.stdout.write(self.style.SUCCESS(f"创建管理员绑定角色: {admin_bindrole}"))
            
        self.stdout.write(self.style.SUCCESS("初始化默认配置完成"))
            
        

        # 添加测试页面
        test_dir_menu = SysMenu.objects.create(
            name="测试目录",
            icon="example",
            parent_id=0,
            order_num=14,
            path="/testPage",
            menu_type="M",
            api_path="/testPage",
            create_time=timezone.now(),
            update_time=timezone.now(),
            remark="测试目录"
        )
        self.stdout.write(self.style.SUCCESS(f"添加测试目录"))
        # 添加测试页面菜单
        SysMenu.objects.create(
            name="测试页面",
            icon="example",
            parent_id=test_dir_menu.id,
            order_num=1,
            path="/testPage",
            menu_type="C",
            api_path="/testPage",
            create_time=timezone.now(),
            update_time=timezone.now(),
            remark="测试页面"
        )
        self.stdout.write(self.style.SUCCESS(f"添加测试页面"))

